package example.SFTP.SFTPexample;


import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.jscape.inet.sftp.*;
import com.jscape.inet.sftp.events.*;
import com.jscape.inet.ssh.util.SshParameters;
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.Enumeration;

public class SFTPDownloadMngr extends SftpAdapter {
    private String ftpHostname;
    private String ftpUsername;
    private String ftpPassword;
    private String filter;
    
    // perform multiple file download
    public File doDownload(String ftpHostname, String ftpUsername, String ftpPassword, String file) throws SftpException, com.jscape.inet.sftp.SftpException {
    		
		// create new SshParameters instance
		SshParameters params = new SshParameters(ftpHostname,ftpUsername,ftpPassword);    		
		    	
		// create new Ftp instance
		Sftp ftp = new Sftp(params);
        
        //capture FTP related events
        ftp.addSftpListener(this);
        
        // establish connection
        ftp.connect();        
        
        // download files matching filter
        File result = ftp.download(file); //mdownload(filter);
        
        // disconnect
        ftp.disconnect();
        
        return result;
    }    
    
    
    // captures download event
    public void download(SftpDownloadEvent evt) {
        System.out.println("Downloaded file: " + evt.getFilename());
    }
    
    // captures connect event
    public void connected(SftpConnectedEvent evt) {
        System.out.println("Connected to server: " + evt.getHostname());
    }
    
    // captures disconnect event
    public void disconnected(SftpDisconnectedEvent evt) {
        System.out.println("Disconnected from server: " + evt.getHostname());
    }
    
	public String readFile(String ftpHostname,String ftpUsername,String ftpPassword, String fileName) throws IOException, SftpException {
		
		File file = doDownload(ftpHostname, ftpUsername, ftpPassword, fileName);
		
		FileInputStream stream = new FileInputStream(file);

			FileChannel fc = stream.getChannel();
			MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0,
					fc.size());
			/* Instead of using default, pass in a decoder. */
			return Charset.defaultCharset().decode(bb).toString();
	}
	
   
}